import { logger } from 'logging/logger';

import { modelSelected } from 'features/parameters/store/actions';
import {
  modelChanged,
  setHeight,
  setWidth,
} from 'features/parameters/store/generationSlice';
import { zMainOrOnnxModel } from 'features/parameters/types/parameterSchemas';

import { startAppListening } from '..';

export const addModelSelectedListener = () => {
  startAppListening({
    actionCreator: modelSelected,
    effect: (action, { getState, dispatch }) => {
      const log = logger('models');

      const state = getState();
      const result = zMainOrOnnxModel.safeParse(action.payload);

      if (!result.success) {
        log.error(
          { error: result.error.format() },
          'Failed to parse main model'
        );
        return;
      }

      const newModel = result.data;

      // Update Width / Height / Bounding Box Dimensions on Model Change
      if (
        state.generation.model?.base_model !== newModel.base_model
      ) {
        if (['sdxl', 'sdxl-refiner'].includes(newModel.base_model)) {
          dispatch(setWidth(1024));
          dispatch(setHeight(1024));
        } else {
          dispatch(setWidth(512));
          dispatch(setHeight(512));
        }
      }

      dispatch(modelChanged(newModel));
    },
  });
};
